package com.starry.androidmvvmexample.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider

abstract class BaseVMFragment<VB : ViewDataBinding, VM : ViewModel>(
    private val viewModelClass: Class<VM>,
    private val inflater: (LayoutInflater) -> VB
) : BaseFragment() {

    /**
     * viewDataBinding
     */
    protected lateinit var mBinding: VB

    /**
     * 通过反射拿到ViewModel并且注册
     */
    protected val mViewModel: VM by lazy {
        ViewModelProvider(this)[viewModelClass]
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        mBinding = inflater(layoutInflater)
        //关联ViewModel
        mBinding.setVariable(initVariableId(), mViewModel)
        //支持LiveData绑定xml，数据改变，UI自动会更新
        mBinding.setLifecycleOwner(this)

        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initParams()//初始化页面接受的参数
        initView()
        initViewObservable()
        initData()
        requestData()
    }

    /**
     * 初始化ViewModel的id
     *
     * @return BR的id
     */
    abstract fun initVariableId(): Int

}